package com.jy.admin.services.cashPocket;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.DateUtil;
import com.fqgj.common.utils.StringUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jsoniter.JsonIterator;
import com.jsoniter.any.Any;
import com.jsoniter.output.JsonStream;
import com.jy.admin.config.ApolloConfigUtil;
import com.jy.admin.db.dao.CeAgentAccountDao;
import com.jy.admin.db.dao.CeCommentPushLogDao;
import com.jy.admin.db.dao.CeMerchantDao;
import com.jy.admin.db.dao.CeOrdersDetailDao;
import com.jy.admin.db.entity.*;
import com.jy.admin.enums.ApiTypeEnum;
import com.jy.admin.enums.DosCollectionTagEnum;
import com.jy.admin.enums.OrderStatusEnum;
import com.jy.admin.enums.OrderSyncStatusEnum;
import com.jy.admin.jobs.BaseJobHandler;
import com.jy.admin.services.BaseCrawlerService;
import com.jy.admin.services.cashPocket.vo.ClOrderInputVo;
import com.jy.admin.services.cashPocket.vo.ClOrderReceiveRequest;
import com.jy.admin.services.cashPocket.vo.ClRepaymentRequest;
import com.jy.admin.services.cashPocket.vo.ClUserInfoInputVo;
import com.jy.bo.common.conf.util.HttpUtil;
import com.robert.vesta.util.IdUtils;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

import static com.jy.bo.common.conf.util.HttpUtil.getIgnoreSslHostnameVerifier;
import static com.jy.bo.common.conf.util.HttpUtil.getSSLSocketFactory;


/**
 * Created with IntelliJ IDEA.
 * User: sm
 * Date: 2022/1/3
 * Time: 8:46 下午
 */
@Service
public class DosService extends BaseCrawlerService {
    private static final Logger LOGGER = LoggerFactory.getLogger(DosService.class);

    @Autowired
    private CeOrdersDetailDao ordersDetailDao;

    @Autowired
    private CeMerchantDao merchantDao;

    @Autowired
    private CeCommentPushLogDao commentPushLogDao;

    @Autowired
    private CeAgentAccountDao agentAccountDao;

    @Autowired
    private ApolloConfigUtil apolloConfigUtil;


    @PostConstruct
    public void init() {
        BaseJobHandler.merchantAndServiceMap.put("dos", this);
        BaseJobHandler.merchantAndServiceMap.put("everymoney", this);
        BaseJobHandler.merchantAndServiceMap.put("swiftcash", this);
        BaseJobHandler.merchantAndServiceMap.put("quickcash", this);
    }


    public String login(String agentCode, String cookie) {
        if (StringUtils.isEmpty(cookie)) {
            return "Cookie 不能为空";
        }
        CeAgentAccountEntity agentAccount = agentAccountDao.getByAgentCode(agentCode);
        LOGGER.info("== dos 登录接口 ==,cookie:{}", cookie);
        if (StringUtils.isNotEmpty(cookie)) {
            JSONObject requestHeader = new JSONObject();
            requestHeader.put("Authentication", cookie);
            requestHeader.put("Content-Type", "application/json");
            agentAccount.setRequestHeader(requestHeader.toString());
            agentAccount.setLoginDt(new Date());
            agentAccount.setLoginStatus(1);
            agentAccountDao.updateByPrimaryKey(agentAccount);
            return "登录成功";
        } else {
            LOGGER.info("== 请求登录接口 失败 ==");
            agentAccount.setLoginStatus(2);
            agentAccountDao.updateByPrimaryKey(agentAccount);
            return "登录失败";
        }
    }

    private static String generateTM() {
        char[] cha = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
        StringBuilder tm = new StringBuilder();
        for (int i = 0; i < 999; i++) {
            int index;
            index = (int) (Math.random() * (cha.length));
            char c = cha[index];
            if (i == 0 && c == '0') {
                continue;
            }
            tm.append(c);
            if (tm.length() == 9) {
                LOGGER.info("====,i:{}", i);
                break;
            }
        }
        return tm.toString();
    }
    private static String getS(String time, String random) {
        String builder = time + time + time +
                random + random +
                time +
                random + random + random + random + random + random + random +
                time + time + time + time + time + time + time +
                random + random + random + random + random + random;
        String firstMd5 = DigestUtils.md5DigestAsHex(builder.getBytes());
        String finalMd5 = DigestUtils.md5DigestAsHex((firstMd5 + random + random + random + random + random).getBytes());
        return finalMd5;
    }
    public static void main(String[] args) {
        String logo="file://https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fsafe-img.xhscdn.com%2Fbw1%2F5832c5ce-fc7a-487d-9ae4-96b77553a55f%3FimageView2%2F2%2Fw%2F1080%2Fformat%2Fjpg&refer=http%3A%2F%2Fsafe-img.xhscdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1689755011&t=6b775855c413280f1767b132f8b5924b";
        if (logo.contains("https://")){
            logo=logo.substring(logo.indexOf("https://"));
        }
//        long timestamp = System.currentTimeMillis();
//        long currentTimeMillis = System.currentTimeMillis();
//        boolean b = System.currentTimeMillis() - timestamp > 3 * 60 * 1000;
//        if (currentTimeMillis - timestamp > 3 * 60 * 1000 || timestamp > currentTimeMillis) {
//            LOGGER.info("====舒服卡");
//
//        }
//        String s = getS(System.currentTimeMillis(), Long.valueOf(generateTM()));
        LOGGER.info("====,s:{}",logo);
    }

    public boolean autoLogin(CeAgentAccountEntity agentAccount) {
        if (apolloConfigUtil.isAutoLoginOpen()) {
            CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
            String url = merchant.getApiDomain() + "/manage/login?username=" + agentAccount.getAccount() + "&password=" + agentAccount.getPassword() + "&capcode=" + System.currentTimeMillis() + "&xpos=160";
            LOGGER.info("== 开始请求登录接口 ==,url:{}", url);
            Map<String, String> headers = Maps.newHashMap();
            JSONObject params = new JSONObject();
            String result = HttpUtil.postPageSsLText(url, headers, params.toString());
            LOGGER.info("== dos请求登录接口 ==,result:{}", result);
            if (JsonIterator.deserialize(result).get("code").toInt() == 200) {
                LOGGER.error("== 请求登录接口 成功==，data:{}", JsonIterator.deserialize(result).get("data").toString());
                JSONObject requestHeader = new JSONObject();
                requestHeader.put("Authentication", JsonIterator.deserialize(result).get("data").get("token").toString());
                requestHeader.put("Content-Type", "application/json");
                agentAccount.setRequestHeader(requestHeader.toString());
                agentAccount.setLoginDt(new Date());
                agentAccount.setLoginStatus(1);
                agentAccountDao.updateByPrimaryKey(agentAccount);
                return true;
            } else {
                LOGGER.info("== 请求登录接口 失败 ==");
                agentAccount.setLoginStatus(2);
                agentAccountDao.updateByPrimaryKey(agentAccount);
                return false;
            }
        } else {
            LOGGER.info("== 请求登录接口 开关未开启 ==");
            agentAccount.setLoginStatus(2);
            agentAccountDao.updateByPrimaryKey(agentAccount);
        }
        return false;
    }


    @Override
    public boolean hasLogin(CeAgentAccountEntity agentAccount) {
        if (apolloConfigUtil.isLoginStatusUseCache()) {
            return agentAccount.getLoginStatus() == 1;
        }

        if (agentAccount.getLoginStatus() == 2) {
            LOGGER.error("== 账号 token不可用 ==,account:{}", agentAccount.getAccount());
//            boolean isLogin = autoLogin(agentAccount);
//            if (!isLogin) {
            return false;
//            }
        }

        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
        try {

            String time = String.valueOf(System.currentTimeMillis());
            String v = generateTM();
            String url = merchant.getApiDomain() + "/manage/urge/repay/myTask?v=" + v + "&repay=false&size=10&current=1&t=" + time +"&s="+getS(time,v);
            Map<String, String> headers = getHeaders(agentAccount);
            LOGGER.info("== 开始请求订单列表 ==,url:{}", url);
            Map<String, String> params = Maps.newHashMap();
            LOGGER.info("== 构建header ==,header:{}", JsonStream.serialize(headers));
            OkHttpClient client = new OkHttpClient()
                    .newBuilder()
                    .sslSocketFactory(getSSLSocketFactory())
                    .hostnameVerifier(getIgnoreSslHostnameVerifier())
                    .build();

            Request request = new Request.Builder()
                    .url(url)
                    .addHeader("Authentication", headers.get("Authentication"))
                    .addHeader("Content-Type", headers.get("Content-Type"))
                    .method("GET", null).build();
            Response response = client.newCall(request).execute();
            String result = response.body().string();
            LOGGER.info("== 结束检测Token是否有效 ==,result:{}", result);

            if (JsonIterator.deserialize(result).get("code").toInt() != 200) {
                LOGGER.error("== 请求接口数据出错 当前账号token无效==，account:{},api:{}", agentAccount.getAccount(), ApiTypeEnum.user_info.getType());
//            return autoLogin(agentAccount);
                agentAccount.setLoginStatus(2);
                agentAccountDao.updateByPrimaryKey(agentAccount);
                return false;
            } else {
                List<String> values = response.headers().values("Authentication");
                if (CollectionUtils.isNotEmpty(values)) {
                    JSONObject requestHeader = new JSONObject();
                    requestHeader.put("Authentication", values.get(0));
                    requestHeader.put("Content-Type", "application/json");
                    agentAccount.setRequestHeader(requestHeader.toString());
                    agentAccount.setLoginDt(new Date());
                    agentAccount.setLoginStatus(1);
                    agentAccountDao.updateByPrimaryKey(agentAccount);
                }
            }
            return true;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public void refresh(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== InfinityCashService 开始刷新数据 ==,account:{}", agentAccount.getAccount());
        updateOrderList(agentAccount);

        LOGGER.info("== 订单数据更新完成 开始更新订单关联数据==，account:{}", agentAccount.getAccount());
        updateOrderDetailInfo(agentAccount);

        LOGGER.info("== 订单关联数据已经更新完成==，account:{}", agentAccount.getAccount());
    }

    @Override
    public void updateOrderList(CeAgentAccountEntity agentAccount) {
        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
        String time = String.valueOf(System.currentTimeMillis());
        String v = generateTM();
        String url = merchant.getApiDomain() + "/manage/urge/repay/myTask?v=" + v + "&repay=false&size=500&current=1&t=" + time +"&s="+getS(time,v)+"&penaltyDayEnd="+apolloConfigUtil.getDosOverdueDay();
        LOGGER.info("== 开始请求订单列表 ==,url:{}", url);
        Map<String, String> headers = getHeaders(agentAccount);
        Map<String, String> params = Maps.newHashMap();
        LOGGER.info("== 构建header ==,header:{}", JsonStream.serialize(headers));
        String result = HttpUtil.getPageSSL(url, params, headers);
        Any resultJson = JsonIterator.deserialize(result);
        if (resultJson.get("code").toInt() != 200) {
            LOGGER.error("== 订单列表请求接口数据出错 ==，account:{},api:{}", agentAccount.getAccount(), ApiTypeEnum.order_list.getType());
            return;
        }
        List<Any> resultsList = resultJson.get("data").get("records").asList();

        if (resultJson.get("data").get("total").toInt() > 500) {
            for (int i = 2; i < 10; i++) {
                String newUrl = merchant.getApiDomain() + "/manage/urge/repay/myTask?v=" + v + "&repay=false&size=500&current=" + i + "&t=" + time+"&s="+getS(time,v)+"&penaltyDayEnd="+apolloConfigUtil.getDosOverdueDay();
                String newResult = HttpUtil.getPageSSL(newUrl, params, headers);
                if (JsonIterator.deserialize(newResult).get("code").toInt() != 200) {
                    return;
                }
                resultsList.addAll(JsonIterator.deserialize(newResult).get("data").get("records").asList());
                if (resultsList.size() >= resultJson.get("data").get("total").toInt()) {
                    break;
                }
            }
        }
        LOGGER.info("== 未还款订单列表 ==,screeningList:{}", JsonStream.serialize(resultsList));
        LOGGER.info("== 未还款订单列表数量 ==,size:{}", resultsList.size());


        //查询今天该账号的所有有效订单
        List<CeOrdersEntity> activeOrders = ordersDao.getTodayListByStatusAndAgent(agentAccount.getAgentCode(), OrderStatusEnum.active.getStatus());

        //更新数据
        LOGGER.info("==当天已经有数据 ==，size:{}", activeOrders.size());

        //对比订单数据
        resultsList.forEach(item -> {
            try {
                String orderNo = item.get("repayId").toString();
                CeOrdersEntity todayOneByOrderNo = ordersDao.getTodayOneByOrderNoAndAgentCode(orderNo, agentAccount.getAgentCode());
                if (todayOneByOrderNo == null) {
                    LOGGER.info("==更新的时候发现有新的订单==,account:{},orderNo:{}", agentAccount.getAccount(), orderNo);
                    CeOrdersEntity ceOrdersEntity = new CeOrdersEntity()
                            .setAgentCode(agentAccount.getAgentCode())
                            .setMerchantCode(agentAccount.getMerchantCode())
                            .setOrderNo(orderNo)
                            .setOrderInfo(item.toString())
                            .setStatus(OrderStatusEnum.active.getStatus())
                            .setCreateDt(new Date())
                            .setCollectionNo(IdUtils.genId() + "");
                    ordersDao.insert(ceOrdersEntity);
                }
            } catch (Exception e) {
                LOGGER.error("== 插入数据发生异常 ==,account:{},loanId:{}", agentAccount.getAccount(), item.get("loanAppId").toString(), e);
            }
        });

        LOGGER.info("== 订单减少 ==，size:{}", resultsList.size());
        activeOrders.forEach(item -> {
            try {
                String id = JsonIterator.deserialize(item.getOrderInfo()).get("repayId").toString();
                boolean hasOrder = false;
                for (int i = 0; i < resultsList.size(); i++) {
                    Any child = resultsList.get(i);
                    String orderNo = child.get("repayId").toString();
                    if (id.equals(orderNo)) {
                        LOGGER.info("== 当前订单存在 ==,account:{},orderNo:{}", agentAccount.getAccount(), orderNo);
                        hasOrder = true;
                        break;
                    }

                }
                if (!hasOrder) {
                    LOGGER.info("== 当前订单不存在 ==,account:{},orderNo:{}", agentAccount.getAccount(), id);
                    if (item.getStatus().equals(OrderStatusEnum.active.getStatus())) {
                        item.setStatus(OrderStatusEnum.updated.getStatus());
                        ordersDao.updateByPrimaryKey(item);
                    }
                }
            } catch (Exception e) {
                LOGGER.error("== 插入数据发生异常 ==,account:{},orderNo:{}", agentAccount.getAccount(), JsonIterator.deserialize(item.getOrderInfo()).get("id").toString(), e);
            }
        });

        LOGGER.info("== 订单刷新处理完成 ==");
    }

    @Override
    public void updateOrderDetailInfo(CeAgentAccountEntity agentAccount) {

        List<CeOrdersEntity> activeOrders = ordersDao.getTodayListByStatusAndAgent(agentAccount.getAgentCode(), OrderStatusEnum.active.getStatus());
        if (CollectionUtils.isEmpty(activeOrders)) {
            return;
        }

        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());

        Map<String, String> headers = getHeaders(agentAccount);
        LOGGER.info("== 构建header ==,header:{}", JsonStream.serialize(headers));


        activeOrders.forEach(order -> {

            try {
                boolean hasDetailData = order.getDetailStatus() == 1;
                Map<String, String> infoMap = new HashMap<>();


                Any orderInfo = JsonIterator.deserialize(order.getOrderInfo());
                String remainMoney = orderInfo.get("repayAmount").toString();
                updateRemainMoney(order.getCollectionNo(), remainMoney);
                String userId = orderInfo.get("userId").toString();
                String time = String.valueOf(System.currentTimeMillis());
                String v = generateTM();
                String repayUrl = merchant.getApiDomain() + "/manage/urge/repay/order/detail/" + userId + "?size=10&current=1&t=" + time + "&v=" + v+"&s="+getS(time,v);
                String repayResult = HttpUtil.getPageSSL(repayUrl, Maps.newHashMap(), headers);
                if (JsonIterator.deserialize(repayResult).get("code").toInt() != 200) {
                    LOGGER.info("== 获取订单详情出错 ==,orderNo:{}", order.getOrderNo());
                    return;
                }
                List<Any> anies = JsonIterator.deserialize(repayResult).get("data").get("records").asList();
                if (CollectionUtils.isNotEmpty(anies)) {
                    anies.forEach(any -> {
                        if (any.get("borrowId").toString().equals(orderInfo.get("borrowId").toString())){
                            infoMap.put("repaymentInfo", any.toString());
                        }
                    });
                }

                JSONObject detailParam = new JSONObject();
                detailParam.put("userId", userId);
                detailParam.put("type", 1);
                detailParam.put("productId", null);
                String detailUrl = merchant.getApiDomain() + "/manage/userInfo/detail?v=" + v + "&t=" + time+"&s="+getS(time,v);
                String detailResult = HttpUtil.postPageBody(detailUrl, headers, detailParam.toString());
                Any detailInfo = JsonIterator.deserialize(detailResult).get("data");
                List<String> images = Lists.newArrayList();
                Any imageInfo = detailInfo.get("imageInfo");
                if (!imageInfo.get("frontImg").toString().equals("")) {
                    images.add(imageInfo.get("frontImg").toString());
                }
                if (!imageInfo.get("backImg").toString().equals("")) {
                    images.add(imageInfo.get("backImg").toString());
                }
                if (!imageInfo.get("panImg").toString().equals("")) {
                    images.add(imageInfo.get("panImg").toString());
                }
                if (!imageInfo.get("selfieImg").toString().equals("")) {
                    images.add(imageInfo.get("selfieImg").toString());
                }
                infoMap.put("images", JsonStream.serialize(images));
                LOGGER.info("== 获取成功 images==");
                updateImages(order.getOrderNo(), JsonStream.serialize(images), order.getMerchantCode());

                if (!hasDetailData) {
                    infoMap.put("baseInfo", detailInfo.get("baseInfo").toString());
                    List<Any> contactList = detailInfo.get("contactInfo").get("contacts").asList();
                    ArrayList<JSONObject> list = Lists.newArrayList();
                    if (CollectionUtils.isNotEmpty(contactList)) {
                        for (int i = 0; i < contactList.size(); i++) {
                            JSONObject j1 = new JSONObject();
                            Any vo = contactList.get(i);
                            j1.put("name", vo.get("name").toString());
                            if (StringUtils.isNotEmpty(vo.get("phone").toString())) {
                                j1.put("phone", vo.get("phone").toString());
                                list.add(j1);
                            }
                        }
                        infoMap.put("contactInfo", list.toString());
                        LOGGER.info("== 获取成功 emergencyInfo==");
                    }
                    try {
                        String contactInfoUrl = merchant.getApiDomain() + "/manage/urge/repay/addressBook/detail/" + userId + "?size=100&current=1&t=" + time + "&v=" + v+"&s="+getS(time,v);
                        Map<String, String> contactParams = Maps.newHashMap();
                        String contactInfo = HttpUtil.getPageSSL(contactInfoUrl, contactParams, headers);
                        LOGGER.info("== 上传通讯录，得到地址 ==,contactInfo:{}", contactInfo);

                        List<Any> contactRecords = JsonIterator.deserialize(contactInfo).get("data").get("records").asList();
                        JSONObject jsonData = new JSONObject();
                        if (CollectionUtils.isNotEmpty(contactRecords)) {
                            JSONArray contacts = new JSONArray();
                            for (Any vo : contactRecords) {
                                JSONObject j1 = new JSONObject();
                                j1.put("name", vo.get("contacts_name").toString());
                                if(vo.get("contacts_phone") != null) {
                                    if (StringUtils.isNotEmpty(vo.get("contacts_phone").toString())) {
                                        if (vo.get("contacts_phone").asList().get(0).toString().length() > 9) {
                                            LOGGER.info("== 上传通讯录，得到地址 ==,url:{}", vo.get("contacts_phone").asList().get(0).toString());
                                            j1.put("phone", vo.get("contacts_phone").asList().get(0).toString());
                                            contacts.add(j1);
                                        }
                                    }
                                }
                            }
                            jsonData.put("contacts", contacts);
                            LOGGER.info("== 上传通讯录，得到地址 ==,url:{}", contacts.toJSONString());
                        } else {
                            jsonData.put("contacts", Lists.newArrayList());
                        }

                        String contactUrl = uploadContact(order.getOrderNo(), jsonData.toString());
                        LOGGER.info("== 上传通讯录，得到地址 ==,url:{}", contactUrl);
                        infoMap.put("contactUrl", contactUrl);
                    } catch (Exception e) {
                        LOGGER.error("== 通讯录转换错误 ==", e);
                    }



                    infoMap.keySet().forEach(k -> {
                        CeOrdersDetailEntity byKeyAndMerchantAndOrderNo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), k, order.getOrderNo());
                        if (byKeyAndMerchantAndOrderNo == null) {
                            CeOrdersDetailEntity ordersDetailEntity = new CeOrdersDetailEntity()
                                    .setOrderNo(order.getOrderNo())
                                    .setMerchantCode(order.getMerchantCode())
                                    .setDataKey(k)
                                    .setDetailInfo(infoMap.get(k));
                            ordersDetailDao.insert(ordersDetailEntity);
                        } else {
                            byKeyAndMerchantAndOrderNo.setDetailInfo(infoMap.get(k));
                            ordersDetailDao.updateByPrimaryKey(byKeyAndMerchantAndOrderNo);
                        }

                    });
                } else {
                    infoMap.keySet().forEach(k -> {
                        CeOrdersDetailEntity byKeyAndMerchantAndOrderNo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), k, order.getOrderNo());
                        byKeyAndMerchantAndOrderNo.setDetailInfo(infoMap.get(k));
                        ordersDetailDao.updateByPrimaryKey(byKeyAndMerchantAndOrderNo);
                    });
                }

                order.setDetailStatus(1);
                ordersDao.updateByPrimaryKey(order);
            } catch (Exception e) {
                LOGGER.error("== 程序处理有异常 ==", e);
                order.setDetailStatus(2);
                ordersDao.updateByPrimaryKey(order);
            }
        });

        LOGGER.info("== 程序处理完成 ==");
    }

    @Override
    public void compostCollectionData(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== compostCollectionData ==");
        List<CeOrdersEntity> todayListBySyncStatusAndAgent = ordersDao.getTodayListBySyncStatusAndAgent(agentAccount.getAgentCode(), OrderSyncStatusEnum.waiting.getStatus());
        if (CollectionUtils.isEmpty(todayListBySyncStatusAndAgent)) {
            LOGGER.info("== compostCollectionData  没有需要同步的订单 ==，agentCode:{},syncStatus:{}", agentAccount.getAgentCode(), OrderSyncStatusEnum.waiting.getStatus());
            return;
        }

        LOGGER.info("== compostCollectionData  需要同步的订单 ==，size:{},account:{}", todayListBySyncStatusAndAgent.size(), agentAccount.getAccount());

        todayListBySyncStatusAndAgent.forEach(order -> {
            try {
                LOGGER.info("== 构建推送信息 基础信息 开始==,collectionNo:{},syncStatus:{}", order.getCollectionNo(), order.getSyncStatus());
                Any orderDetail = JsonIterator.deserialize(order.getOrderInfo());
                String appName = orderDetail.get("appName").toString() + "[" + orderDetail.get("productName").toString() + "]";
                ClOrderReceiveRequest request = new ClOrderReceiveRequest()
                        .setOrderBillNo(order.getCollectionNo())
                        .setTradeNo(order.getCollectionNo())
                        .setProductType(appName)
                        .setAppName(appName)
                        .setOriginOrderNo(order.getOrderNo())
                        .setAccount(order.getAgentCode())
                        .setAccount_id(agentAccount.getId())
                        .setClientCode(order.getMerchantCode())
                        .setProductCode(appName)
                        .setUserCode(IdUtils.genId() + "");


                CeOrdersDetailEntity repaymentInfoDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNoToday(order.getMerchantCode(), "repaymentInfo", order.getOrderNo());
                Any repaymentInfo = JsonIterator.deserialize(repaymentInfoDetail.getDetailInfo());
                String borrowCapital = repaymentInfo.get("principal").toString();
                String actualAmount = repaymentInfo.get("principal").toString();
                String repaymentAmount = repaymentInfo.get("contractRepaymentAmount").toString();
                String remainMoney = repaymentInfo.get("contractRepaymentAmount").toString();
                String overdueDays = orderDetail.get("penaltyDay").toString();
                String loanInterest = repaymentInfo.get("interest").toString();
                String rearFee = repaymentInfo.get("rearFee").toString();
                String lateFee = repaymentInfo.get("penaltyAmout").toString().equals("") ? repaymentInfo.get("penaltyAmount").toString() : repaymentInfo.get("penaltyAmout").toString();
                Integer userType = orderDetail.get("isReloan").toInt();
                LOGGER.info("== 构建推送信息 计算逾期罚息利率 开始==,borrowCapital:{}，overdueDays:{}.lateFee:{}", borrowCapital, overdueDays, lateFee);
                String overdueRatio = "0";
                LOGGER.info("== 构建推送信息 计算逾期罚息利率 开始==,borrowCapital:{}，overdueDays:{}.lateFee:{}", borrowCapital, overdueDays, lateFee);
                if (!overdueDays.equals("0")) {
                    overdueRatio = new BigDecimal(lateFee).divide(new BigDecimal(overdueDays), 2, BigDecimal.ROUND_HALF_UP).divide(new BigDecimal(borrowCapital), 4, BigDecimal.ROUND_HALF_UP).toString();
                }
                String shouldRepayTime = repaymentInfo.get("repayTime").toString();
                String applyLoanTime = repaymentInfo.get("applyLoanTime").toString();
                String converseDate = DateUtil.getConverseDate(shouldRepayTime, 6);
                LOGGER.info("== 构建推送信息 订单信息 开始==,collectionNo:{}", order.getCollectionNo());
                ClOrderInputVo orderInputVo = new ClOrderInputVo()
                        .setBorrowType(userType == 0 ? 1 : 2)
                        .setBorrowCapital(borrowCapital)
                        .setAppLink("")
                        .setChannel(appName)
                        .setCapitalCode(appName)
                        .setInterest(loanInterest)
                        .setDeductAmount("0")
                        .setLateFeeRatio(overdueRatio)
                        .setServiceFee(rearFee)
                        .setLateServiceFee("0")
                        .setReceivedCapital(actualAmount)
                        .setPaidAmount("0")
                        .setReceivedDate(applyLoanTime)
                        .setRepaymentDate(shouldRepayTime)
                        .setRemainMoney(remainMoney)
                        .setTotalMoney(repaymentAmount);

                request.setOrderInfo(orderInputVo);

                CeOrdersDetailEntity baseInfoDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNoToday(order.getMerchantCode(), "baseInfo", order.getOrderNo());
                Any baseInfo = JsonIterator.deserialize(baseInfoDetail.getDetailInfo());
                LOGGER.info("== 构建推送信息 个人信息 开始==,collectionNo:{}", order.getCollectionNo());

                String aadhaarNo = baseInfo.get("idNo").toString();
                String pancardNo = baseInfo.get("panCode").toString();
                String email = "no";
                String mobile = baseInfo.get("phone").toString();
                String name = baseInfo.get("realName").toString();
                String state = "no";
                Integer gender = baseInfo.get("sex").toInt();
                int maritalStatus = 0;
                int education = 0;
                String address = baseInfo.get("address").toString();
                String pinCode = "no";
                String city = "no";
                String birthDay = DateUtil.getDate(DateUtil.getDate(baseInfo.get("dateOfBirth").toString(), "dd/MM/yyyy"), "yyyy-MM-dd");

                CeOrdersDetailEntity contactInfo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "contactInfo", order.getOrderNo());
                List<Any> contactInfoJson = JsonIterator.deserialize(contactInfo.getDetailInfo()).asList();

                String parentName = "no";
                String parentPhone = "no";
                String friendName = "no";
                String friendMobile = "no";
                if (contactInfoJson.size() > 2) {
                    parentName = contactInfoJson.get(1).get("name").toString();
                    parentPhone = contactInfoJson.get(1).get("phone").toString();
                    friendName = contactInfoJson.get(2).get("name").toString();
                    friendMobile = contactInfoJson.get(2).get("phone").toString();
                }


                CeOrdersDetailEntity contactUrlEntity = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "contactUrl", order.getOrderNo());


                CeOrdersDetailEntity iamges = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "images", order.getOrderNo());
                List<Any> anies = JsonIterator.deserialize(iamges.getDetailInfo()).asList();

                List<String> images = new ArrayList<>();
                anies.forEach(v -> {
                    images.add(v.toString());
                });

                ClUserInfoInputVo userInfoInputVo = new ClUserInfoInputVo()
                        .setUserLanguage("")
                        .setAadhaarNo(aadhaarNo)
                        .setPanCardNo(pancardNo)
                        .setAddress(address)
                        .setBirthday(birthDay)
                        .setCity(city)
                        .setEmail(email)

                        .setContact1Mobile(parentPhone)
                        .setContact1Name(parentName)
                        .setContact1Relative(1)

                        .setContact2Mobile(friendMobile)
                        .setContact2Name(friendName)
                        .setContact2Relative(6)

                        .setEducation(education)
                        .setKycNo(aadhaarNo)
                        .setMobile(mobile)

                        .setMarriedStatus(maritalStatus)
                        .setMarriedStatus(maritalStatus)
                        .setName(name)
                        .setPinCode(pinCode)
                        .setState(state)

                        .setSex(gender)
                        .setContactUrl(contactUrlEntity!=null?contactUrlEntity.getDetailInfo() : "")
                        .setImages(images);

                request.setUserInfo(userInfoInputVo);

                LOGGER.info("== 构建推送信息 完成==,collectionNo:{}", order.getCollectionNo());

                CePushLogEntity pushLogEntity = pushLogDao.selectByCollectionNo(order.getCollectionNo());
                if (pushLogEntity == null) {
                    pushLogEntity = new CePushLogEntity()
                            .setCollectionNo(order.getCollectionNo())
                            .setDetailInfo(JsonStream.serialize(request))
                            .setStatus(1);
                    pushLogDao.insert(pushLogEntity);
                } else {
                    pushLogEntity.setDetailInfo(JsonStream.serialize(request));
                    pushLogDao.updateByPrimaryKey(pushLogEntity);
                }


                LOGGER.info("== 构建推送信息 保存信息完成==,collectionNo:{}", order.getCollectionNo());
                order.setSyncStatus(OrderSyncStatusEnum.data_ready.getStatus());
                ordersDao.updateByPrimaryKey(order);
            } catch (Exception e) {
                LOGGER.error("== 构建推送信息 发生异常==,collectionNo:{}", order.getCollectionNo(), e);
                order.setSyncStatus(OrderSyncStatusEnum.data_fail.getStatus());
                ordersDao.updateByPrimaryKey(order);
            }
        });

    }

    @Override
    public void pushDataToCollection(CeAgentAccountEntity agentAccount) {
        super.pushDataToCollection(agentAccount);
    }

    /**
     * 获取新的借贷信息的详细内容是需要 在这个方法执行之前的
     *
     * @param agentAccount
     */
    @Override
    public void checkOrdersPaidStatus(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== 检查订单支付情况 ==");
        List<CeOrdersEntity> waitingPaidCheckOrders = ordersDao.getTodayListByStatusAndAgent(agentAccount.getAgentCode(), OrderStatusEnum.updated.getStatus());
        if (CollectionUtils.isEmpty(waitingPaidCheckOrders)) {
            LOGGER.info("== 检查订单支付情况 没有状态更新的订单==,size:{}", waitingPaidCheckOrders.size());
            return;
        }

        LOGGER.info("== 检查订单支付情况==,size:{}", waitingPaidCheckOrders.size());
        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
        String time = String.valueOf(System.currentTimeMillis());
        String v = generateTM();
        String url = merchant.getApiDomain() + "/manage/urge/repay/myTask?repay=true&size=500&current=1&t=" + time + "&v=" + v +"&s="+getS(time,v)+"&repaySuccessTimeStart="+DateUtil.getDate("yyyy-MM-dd")+"+00:00:00"+"&repaySuccessTimeEnd="+DateUtil.getDate("yyyy-MM-dd")+"+23:59:59";
        LOGGER.info("== 开始请求订单列表 ==,url:{}", url);
        Map<String, String> headers = getHeaders(agentAccount);
        Map<String, String> params = Maps.newHashMap();
        LOGGER.info("== 构建header ==,header:{}", JsonStream.serialize(headers));
        String result = HttpUtil.getPageSSL(url, params, headers);
        Any resultJson = JsonIterator.deserialize(result);
        if (resultJson.get("code").toInt() != 200) {
            LOGGER.error("== 订单列表请求接口数据出错 ==，account:{},api:{}", agentAccount.getAccount(), ApiTypeEnum.order_list.getType());
            return;
        }

        List<Any> resultsList = resultJson.get("data").get("records").asList();
        LOGGER.info("== 已还款订单列表 ==,screeningList:{}", JsonStream.serialize(resultsList));

        waitingPaidCheckOrders.forEach(order -> {
            boolean isRepay = false;
            String successLoanAppId = order.getOrderNo();
            for (Any any : resultsList) {
                String loanAppId = any.get("repayId").toString();
                if (loanAppId.equals(successLoanAppId)) {
                    isRepay = true;
                    break;
                }
            }

            if (isRepay) {
                LOGGER.info("== 订单已还款 ==,OrderNo:{}", order.getOrderNo());
                order.setSyncStatus(OrderSyncStatusEnum.need_pay_update.getStatus());
                order.setStatus(OrderStatusEnum.paid_update.getStatus());
                ordersDao.updateByPrimaryKey(order);
                return;
            }
            LOGGER.info("== 订单未还款，移除订单 ==,orderNo:{}", order.getOrderNo());

            order.setStatus(OrderStatusEnum.removed.getStatus());
            order.setSyncStatus(OrderSyncStatusEnum.need_remove.getStatus());
            ordersDao.updateByPrimaryKey(order);
        });

    }

    @Override
    public void updatePaidOrderToCollection(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== 开始同步有更新的数据到催收系统 ==");
        List<CeOrdersEntity> todayListBySyncStatusAndAgent = ordersDao.getTodayListBySyncStatusAndAgent(agentAccount.getAgentCode(), OrderSyncStatusEnum.need_pay_update.getStatus());
        if (CollectionUtils.isEmpty(todayListBySyncStatusAndAgent)) {
            LOGGER.info("== 开始同步有更新的数据到催收系统 没有还款订单==");
            return;
        }

        LOGGER.info("== 开始同步有更新的数据到催收系统 有还款==,size:{}", todayListBySyncStatusAndAgent.size());
        todayListBySyncStatusAndAgent.forEach(order -> {
            try {
                Any repaymentInfo = JsonIterator.deserialize(order.getOrderInfo());
                String paidAmount = "0";
                ClRepaymentRequest request = new ClRepaymentRequest()
                        .setDeductAmount("0")
                        .setOrderBillNo(order.getCollectionNo())
                        .setPaidAmount(paidAmount)
                        .setPaidStatus(2)
                        .setPaidType(1)
                        .setRepayBizNo(IdUtils.genId() + "")
                        .setRepayDate(DateUtil.getDate(new Date(), "yyyy-MM-dd HH:mm:ss"))
                        .setToken("a481e307fd3343c4faca93ADAFb8a3892ee1")
                        .setTotalDeductAmount("0")
                        .setTotalPaidAmount(paidAmount)
                        .setTradeNo(order.getCollectionNo());

                HttpHeaders headers = new HttpHeaders();
                headers.set("Content-Type", "application/json;charset=utf-8");

                HttpEntity requestPush = new HttpEntity(JsonStream.serialize(request), headers);
                ResponseEntity responseEntity = new RestTemplate().postForEntity(apolloConfigUtil.getCollectionRepayPushUrl(), requestPush, String.class);
                String responseStr = responseEntity.getBody().toString();
                LOGGER.info("=======  推送collection请求结果  ======:{},method:{}", responseStr, apolloConfigUtil.getCollectionRepayPushUrl());
                if (JsonIterator.deserialize(responseStr).get("code").toString().equals("0")) {
                    LOGGER.info("== 开始同步有更新的数据到催收系统 推送还款成功==,orderNo:{}", order.getOrderNo());
                    order.setSyncStatus(OrderSyncStatusEnum.pay_update_success.getStatus());
                } else {
                    LOGGER.error("== 开始同步有更新的数据到催收系统 推送还款失败==,orderNo:{}", order.getOrderNo());
                    order.setSyncStatus(OrderSyncStatusEnum.pay_update_fail.getStatus());
                }
            } catch (Exception e) {
                LOGGER.error("=======  推送collection请求结果 error  ======", e);
                order.setSyncStatus(OrderSyncStatusEnum.pay_update_fail.getStatus());
            }
            ordersDao.updateByPrimaryKey(order);
        });


    }


    @Override
    public void updateRemovedOrderToCollection(CeAgentAccountEntity agentAccount) {
        LOGGER.info("==  updateRemovedOrderToCollection 开始同步有更新的数据到催收系统 ==");
//        List<CeOrdersEntity> todayListBySyncStatusAndAgent = ordersDao.getTodayListBySyncStatusAndAgent(agentAccount.getAgentCode(), OrderSyncStatusEnum.need_remove.getStatus());
//        if (CollectionUtils.isEmpty(todayListBySyncStatusAndAgent)) {
//            LOGGER.info("== 开始同步有更新的数据到催收系统 updateRemovedOrderToCollection 没有需要移除的订单==");
//            return;
//        }
//
//        LOGGER.info("== 开始同步有更新的数据到催收系统 updateRemovedOrderToCollection 有数据需要移除==,size:{}", todayListBySyncStatusAndAgent.size());
//        todayListBySyncStatusAndAgent.forEach(order -> {
//            try {
//                CeOrdersDetailEntity repaymentInfoDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNoToday(order.getMerchantCode(), "repaymentInfo", order.getOrderNo());
//                Any repaymentInfo = JsonIterator.deserialize(repaymentInfoDetail.getDetailInfo());
//                String paidAmount = repaymentInfo.get("paidAmount").toString().equals("") ? "0" : repaymentInfo.get("paidAmount").toString());
//                ClRepaymentRequest request = new ClRepaymentRequest()
//                        .setDeductAmount("0")
//                        .setOrderBillNo(order.getCollectionNo())
//                        .setPaidAmount(paidAmount)
//                        .setPaidStatus(2)
//                        .setPaidType(1)
//                        .setRepayBizNo(IdUtils.genId() + "")
//                        .setRepayDate(DateUtil.getDate(new Date(), "yyyy-MM-dd HH:mm:ss"))
//                        .setToken("a481e307fd3343c4faca93ADAFb8a3892ee1")
//                        .setTotalDeductAmount("0")
//                        .setTotalPaidAmount(paidAmount)
//                        .setTradeNo(order.getCollectionNo());
//
//                HttpHeaders headers = new HttpHeaders();
//                headers.set("Content-Type", "application/json;charset=utf-8");
//
//                HttpEntity requestPush = new HttpEntity(JsonStream.serialize(request), headers);
//                ResponseEntity responseEntity = new RestTemplate().postForEntity(apolloConfigUtil.getCollectionRepayPushUrl()_remove, requestPush, String.class);
//                String responseStr = responseEntity.getBody().toString();
//                LOGGER.info("=======  推送collection请求结果  ======:{},method:{}", responseStr, apolloConfigUtil.getCollectionRepayPushUrl()_remove);
//                if (JsonIterator.deserialize(responseStr).get("code").toString().equals("0")) {
//                    LOGGER.info("== 开始同步有更新的数据到催收系统 推送还款成功==,orderNo:{}", order.getOrderNo());
//                    order.setSyncStatus(OrderSyncStatusEnum.remove_success.getStatus());
//                } else {
//                    LOGGER.error("== 开始同步有更新的数据到催收系统 推送还款失败==,orderNo:{}", order.getOrderNo());
//                    order.setSyncStatus(OrderSyncStatusEnum.remove_failed.getStatus());
//                }
//            } catch (Exception e) {
//                LOGGER.error("=======  推送collection请求结果 error  ======", e);
//                order.setSyncStatus(OrderSyncStatusEnum.remove_failed.getStatus());
//            }
//            ordersDao.updateByPrimaryKey(order);
//        });


    }

    @Override
    public void composeNote(CeCommentPushLogEntity ceCommentPushLogEntity) {
        ceCommentPushLogEntity.setStatus(1);
        commentPushLogDao.updateByPrimaryKey(ceCommentPushLogEntity);
    }


    @Override
    public boolean sendNote(CeCommentPushLogEntity ceCommentPushLogEntity) {

        DosCollectionTagEnum currentTag = DosCollectionTagEnum.RNR_V2;

        for (DosCollectionTagEnum e : DosCollectionTagEnum.values()) {
            if (e.getType().equals(ceCommentPushLogEntity.getTargetType())) {
                currentTag = e;
            }
        }
        LOGGER.info("== 开始同步催记到甲方 ==");
        CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(ceCommentPushLogEntity.getMerchantCode());
        CeAgentAccountEntity account = agentAccountDao.getByAgentCode(ceCommentPushLogEntity.getAgentCode());
        CeOrdersEntity ceOrdersEntity = ordersDao.getOneByOrderNoAndAgentCode(ceCommentPushLogEntity.getOriginNo(), account.getAgentCode());
        Any orderInfo = JsonIterator.deserialize(ceOrdersEntity.getOrderInfo());
        try {
            Map<String, String> headers = getHeaders(account);
            JSONObject params = new JSONObject();
            ArrayList<Integer> productIds = Lists.newArrayList();
            if ("Credit Loan".equals(orderInfo.get("productName").toString())) {
                productIds.add(2);
            } else {
                productIds.add(1);
            }
            params.put("nextTime", DateUtil.getDate("yyyy-MM-dd HH:mm:ss"));
            params.put("phone", orderInfo.get("phone").toString());
            params.put("phoneStatus", currentTag.getContactType());
            params.put("phoneType", 10);
            params.put("productIds", productIds);
            params.put("promisedRepayTime", orderInfo.get("promisedRepayTime").object());
            params.put("remark", currentTag.getShortDesc());
            params.put("repayUserFeedback", currentTag.getRemarkType());
            params.put("urgeTaskId", orderInfo.get("id").toInt());
            params.put("userId", orderInfo.get("userId").toInt());

            LOGGER.info("== Dos 开始同步催记到甲方D ==,params:{}", JsonStream.serialize(params));
            String time = String.valueOf(System.currentTimeMillis());
            String v = generateTM();
            String noteUrl = ceMerchantEntity.getApiDomain() + "/manage/urge/repay/add/record?t=" +time+ "&v=" + v+"&s="+getS(time,v);
            String result = HttpUtil.postPageBody(noteUrl, headers, params.toString());
            LOGGER.info("== Dos 开始同步催记到甲方 ==,res:{}", result);

            if (JsonIterator.deserialize(result).get("code").toInt() == 200) {
                LOGGER.info("== 开始同步催记到甲方 success==");
                return true;
            } else {
                LOGGER.error("== 开始同步催记到甲方 error==,msg:{}", JsonIterator.deserialize(result).get("msg").toString());
            }

        } catch (Exception e) {
            LOGGER.error("== 开始同步催记到甲方 exception==", e);
        }
        return false;
    }

    @Override
    public String updateRepaymentLink(String collectionNo, boolean isReduce) {
        CeOrdersEntity ceOrdersEntity = ordersDao.getOneByCollectionNo(collectionNo);
        CeAgentAccountEntity accountEntity = agentAccountDao.getByAgentCode(ceOrdersEntity.getAgentCode());
        CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(ceOrdersEntity.getMerchantCode());
        Any orderInfoJson = JsonIterator.deserialize(ceOrdersEntity.getOrderInfo());

        Map<String, String> headers = getHeaders(accountEntity);
        String link = "No Link";
        String time = String.valueOf(System.currentTimeMillis());
        String v = generateTM();
        String url = ceMerchantEntity.getApiDomain() + "/manage/urge/repay/h5/link?t=" + System.currentTimeMillis() + "&userId=" + orderInfoJson.get("userId").toString() + "&repayId=" + orderInfoJson.get("repayId").toString() + "&t=" + time + "&v=" +v+"&s="+getS(time,v);
        String result = HttpUtil.getPageSSL(url,new HashMap<>(), headers);
        LOGGER.info("==获取还款链接==,url:{},result:{}",url,result);
        if (JsonIterator.deserialize(result).get("code").toInt() == 200) {
            link = JsonIterator.deserialize(result).get("data").get("data").get("repayment").toString();
        }
        return link;
    }

    @Override
    public String updateExtensionRepaymentLink(String collectionNo, boolean isOpen) {
        CeOrdersEntity ceOrdersEntity = ordersDao.getOneByCollectionNo(collectionNo);
        CeAgentAccountEntity accountEntity = agentAccountDao.getByAgentCode(ceOrdersEntity.getAgentCode());
        CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(ceOrdersEntity.getMerchantCode());
        Any orderInfoJson = JsonIterator.deserialize(ceOrdersEntity.getOrderInfo());

        Map<String, String> headers = getHeaders(accountEntity);

        String link = "No Link";
        String time = String.valueOf(System.currentTimeMillis());
        String v = generateTM();
        String url = ceMerchantEntity.getApiDomain() + "/manage/urge/repay/h5/link?t=" + System.currentTimeMillis() + "&userId=" + orderInfoJson.get("userId").toString() + "&repayId=" + orderInfoJson.get("repayId").toString() + "&t=" + time + "&v=" + v+"&s="+getS(time,v);

        String result = HttpUtil.getPageSSL(url, Maps.newHashMap(), headers);
        LOGGER.info("==获取展期链接==,url:{},result:{}",url,result);

        if (JsonIterator.deserialize(result).get("code").toInt() == 200) {
            link = JsonIterator.deserialize(result).get("data").get("data").get("extension").toString();
        }
        return link;
    }

    @Override
    public String addPaymentOrder(String orderNo, String fileName, String fileUrl, String utr, String remark, String amount) {
        return "";
    }

    @Override
    public String queryPaymentOrderResult(String orderNo, String utr) {
        return "";
    }

    @Override
    public String checkOrdersPaid(String orderNo) {
        return null;
    }



}
